(function (moduleName4Html, global, factory) {
    if (typeof module !== 'undefined' && typeof exports === 'object') {//CommonJS(NodeJS)
        module.exports = factory(global);
    } else if (typeof define === 'function' && (define.amd || define.cmd)) {//AMD   CMD
        define( function () { factory(global); } );
    } else {//ES(Browser)
        global[moduleName4Html] = factory(global);
    }
}("pageData", this, function (global) {
    'use strict';
    var allNum = 0,
        collectClassifyID='',
       pageData = {
        documentType:{
                'CEB':'application/x-cedx',
                'text':'text/plain;charset=utf-8',
                'doc': 'application/msword;charset=utf-8',
                'docx': 'application/msword;charset=utf-8',
                'pdf':'application/pdf;charset=utf-8',
                'xlm': 'application/vnd.ms-excel',
                'xls':'application/vnd.ms-excel',
                'xlsx':'application/vnd.ms-excel',
                'zip':'application/zip;charset=utf-8',
                'ppt':'application/vnd.ms-powerpoint',
                'xsl' : 'text/xml'
        },
        //弹出收藏弹窗
        savePop:function(popId,targetId,type,target){
            // 判断是否登录
             // 弹出弹窗
             var pop=layer.open({
                 title: '收藏分类',
                 icon: 1,
                 scrollbar: true,
                 type: 1,
                 anim: 2,
                 skin: 'layui-layer-rim', //加上边框
                 area: ['400px', '500px'], //宽高
                 content: $(popId),//这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                 success:function(){
                     $('.new').show(); 
                     $('.newinput').hide(); 
                 }
             });
        pageData.getSaveData(targetId);
        // 点击选中状态
        $('#saveClassify ul').off().on('click',function(e){
            e.stopPropagation();
            e.preventDefault();
            if($(e.target).hasClass('one')){
                var index1=$(e.target).index();
                collectClassifyID=$(e.target).attr('data-id');
            }else{
               // 获取id
                var index1=$(e.target).parent('li').index();
                collectClassifyID=$(e.target).parent('li').attr('data-id');
            }
          $('#saveClassify li').each(function(index,item){
              if(index1==index){
                $(item).addClass('active');
              }else{
                $(item).removeClass('active');
              }
          })
        })
        // 隐藏输入框
        $('.newinput').hide();
        $('.new').off().on('click',function(){
            $('.newinput').show(); 
            $('.new').hide(); 
        })
        $('.createName').off().on('click',function(){            
         //判断输入框是否有值
            if(!$('#ducName').val()){
                return
            }
            $('.new').show(); 
            $('.newinput').hide();
            // 添加文件夹
            shared.ajaxPost(config.addSaveClassify, { collectName: $('#ducName').val(),sort: '1' }, function callback(res1) {
                if (res1.id) {
                    layer.msg('新建文件夹分类成功！',{ time: 1600})
                    // 添加该节点
                   pageData.getSaveData(targetId);
                }
            });
        })
        // 点击确定 
        $('#saveClassify .surebtn').off().on('click',function(e) {
            if(!collectClassifyID){
                layer.msg('您还未创建文件夹!')
               return
            }
            if(type=='inner'){
                pageData.isVisited(target, config.insertCollection, target.attr('data-ipAddress'),collectClassifyID);
            }else{
                pageData.isOutVisited(target, config.insertCollection,collectClassifyID)
            }
            layer.close(pop);
          })
        },
        threePart:function(dataDetail,res){
          //下载
            if($(res).hasClass('download')){
                pageData.InsertLog($(res).attr('data-dbname'),'下载',$(res).attr('data-title'))
                shared.ajaxPost(config.common_onlineDownload,{sysId:dataDetail.sysId,tableCode:dataDetail.tableCode,digitFileName:dataDetail.digitFileName}, function callback(res1) { 
                //   下载成功记录
                    pageData.isVisited(res,config.insertDown, $(res).attr('data-ipAddress'))
               
                    var documentName=dataDetail.digitFileName.split('.');  
                 //文件类型转成小写 
                    var name=  documentName[ documentName.length-1].toLowerCase();
                    var pdfAsArray = pageData.convertDataURIToBinary(res1);
                    var href =window.URL.createObjectURL(new Blob([pdfAsArray], {type:pageData.documentType[name]}));
                    //兼容ie
                    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
                        window.navigator.msSaveOrOpenBlob(new Blob([pdfAsArray], {type:pageData.documentType[name]}),dataDetail.digitFileName);
                      }else{
                     // 兼容谷歌
                      var downloadElement = document.createElement('a')
                      downloadElement.style.display = 'none'
                      downloadElement.href = href
                      downloadElement.download =dataDetail.digitFileName //下载后文件名
                      document.body.appendChild(downloadElement)
                      downloadElement.click() //点击下载
                      document.body.removeChild(downloadElement) //下载完成移除元素
                      window.URL.revokeObjectURL(href) //释放掉blob对象
                   }
             },{ responseType: 'arraybuffer'});   
            }//预览
            else if($(res).hasClass('preview')){
                shared.ajaxPost(config.common_onlineView,{sysId:dataDetail.sysId,tableCode:dataDetail.tableCode,digitFileName:dataDetail.digitFileName}, function callback(res1) {  
                    var documentName=dataDetail.digitFileName.split('.')
                    var name= documentName[ documentName.length-1].toLowerCase();
                    var pdfAsArray = pageData.convertDataURIToBinary(res1);
                    var url =window.URL.createObjectURL(new Blob([pdfAsArray],{type:pageData.documentType[name]}));
                    //预览pdf
                    if(name=='pdf'){
                        window.open('/lib/pdf/web/viewer.html?file=' + encodeURIComponent(url))
                    }
                },{ responseType: 'arraybuffer'}) 

             }
        },
        convertDataURIToBinary:function (dataURI) {   //编码转换
            var raw = window.atob(dataURI);//这个方法在ie内核下无法正常解析。
            var rawLength = raw.length;
            //转换成pdf.js能直接解析的Uint8Array类型
            var array = new Uint8Array(new ArrayBuffer(rawLength));
            for (var i = 0; i < rawLength; i++) {
                array[i] = raw.charCodeAt(i) & 0xff;
            }
            return array;
        },
        getSaveData:function(targetId){
            //获取收藏分类数据
               shared.ajaxPost(config.showSaveClassify, {}, function callback(res) {
               core.useTemplateAuto(targetId,res, {
                   isClass:function(data,index){
                       if(!index){
                        collectClassifyID=data.id;
                           return 'one active';
                       }else{
                           return 'one'
                       }
                   }
               })
           });
        },
        // 预览
        isYLVisited:function(e,url){
            shared.ajaxPost(url, {
                resourceId: e.sysId,
                dbCode:e.tableCode,
                title:e.title,
                dbname: e.dataSource,
                detailUrl: window.location.pathname,
                ipAddress: window.location.search,
            }, function callback(res1) {});
            pageData.InsertLog(e.dataSource,'浏览',e.title)  
        },
        // 收藏 下载 插入值 
        isVisited:function(e,url,ipAddress,collectClassifyID){
            var data= {
                resourceId: e.attr('data-sysid'),
                dbCode:e.attr('data-tablename'),
                title:e.attr('data-title'), 
                dbname:e.attr('data-dbname'),
                detailUrl: window.location.pathname,
                ipAddress: ipAddress,
            }
            if(url==config.insertCollection){
                data.collectClassifyID=collectClassifyID;
            }
            shared.ajaxPost(url,data, function callback(res1) {
                if(url==config.insertCollection){
                    layer.msg(res1)
                }
            });
        },
        isOutVisited:function(e,url,collectClassifyID){
            var loadUrl = config.getOutResourceDetail.replace('{0}', e.attr('data-tablename'));
            var toUrl = loadUrl.replace('{1}',e.attr('data-filename'))
            var data= {
                resourceId: e.attr('data-filename'),
                dbCode:e.attr('data-tablename'),
                title:e.attr('data-title'), 
                dbname:e.attr('data-dbname'),
                detailUrl:toUrl,
                ipAddress:''
            }
            if(url==config.insertCollection){
                data.collectClassifyID=collectClassifyID;
            }
            shared.ajaxPost(url,data, function callback(res1) {
                if(url==config.insertCollection){
                    layer.msg(res1)
                }
            });
        },
        toWwqk:function(mid){
            var loadUrl1 = config.fzww.replace('{1}',mid);
            window.open(loadUrl1)
            $('#meta').attr('content',"default" )
        },
        toCnki:function(code){
            var loadUrl = config.kns.replace('{1}',code);
            var toUrl = loadUrl.replace('{2}',code)
             $('#meta').attr('content',"no-referrer")
            window.open(toUrl)
             $('#meta').attr('content',"default" )
        },
        // 统计下载、检索，浏览
        InsertLog:function(source,accessType,fileName){
            shared.ajaxPost(config.InsertLog, {
                source:source,accessType:accessType,fileName:fileName
            }, function callback(res1) {});
        },
        toOuter:function(e){
            var loadUrl = config.getOutResourceDetail.replace('{0}', e.attr('data-tablename'));
            var toUrl = loadUrl.replace('{1}',e.attr('data-filename'))
            pageData.InsertLog(e.attr('data-dbsource'),'浏览',e.attr('data-title')) 
            window.open(toUrl)
        },
        showNum:function(list,current,pageNum,space){
            //如果显示条数小于当前页选择的显示条数。添加剩余数量
            if (list&&list.length) {
                //添加编号
                for (var t = 0; t < list.length; t++) {
                    list[t]['num'] = t + 1 + (current - 1) * pageNum;
                 }
                 //插入空白
                if (list.length < pageNum&&!space) {
                    var size = pageNum - list.length;
                        for (var i = 0; i < size; i++) {
                                list.push({})
                        }
                    }
                }
        },
       // 使用layui分页
       tableData:function(url,postTableData,tableId, pageId,showNum,mention,render,space,callBackPage,imits){
                shared.ajaxPost(url, postTableData, function callback(res) {
                    console.log(res)
                      if(showNum){
                          pageData.showNum(res.list, postTableData.page, postTableData.pageSize,space);
                      } 
                          //当删除完当前页面索有数据时，返回上一页,排除首次加载
                      if(!res.list.length&&res.count){
                           postTableData.page = postTableData.page -1;
                           //每页显示的条数
                           pageData.renderTableData(url, postTableData,tableId,showNum,mention,render,space);
                       } else{
                             //   如果无数据
                          if(!res.list.length||!res.list){
                            $(mention).css('display','block');
                          }else{
                            $(mention).css('display','none');
                          }
                            core.useTemplateAuto(tableId, res.list,render) 
                       } 
                    layui.use('laypage', function () {
                        var laypage = layui.laypage;
                        //执行一个laypage实例
                        laypage.render({
                            curr:postTableData.page,
                            elem: pageId, //注意，是 ID，不用加 # 号
                            count: res.count,//数据总数，从服务端得到'
                            layout: ['count', 'prev', 'page', 'next', 'limit', 'skip'],
                            first: '首页',
                            last: '尾页',
                            limit: postTableData.pageSize,
                            limits:imits|| [10, 20, 30, 40, 50],
                            groups: 4,
                            prev: '上一页',
                            next: '下一页',
                            jump: function (obj, first) {
                                    // callback 把obj.curr，obj.limit传回去
                                    callBackPage&&callBackPage(obj.curr,obj.limit);
                                //首次加载不执行
                                if (!first) {
                                    postTableData.page = obj.curr;
                                    //每页显示的条数
                                    postTableData.pageSize = obj.limit;
                                    pageData.renderTableData(url, postTableData,tableId,showNum,mention,render,space);
                                }
                            }
                        });
                    });
                },{async:true})
     },
    renderTableData:function (url, postTableData,id,showNum,mention,render,space) {
                shared.ajaxPost(url, postTableData, function callback(res) {
                    if(showNum){
                        pageData.showNum(res.list, postTableData.page, postTableData.pageSize,space);
                    } 
                    // 如果无数据
                    if(!res.list.length||!res.list){
                        $(mention).css('display','block');
                    }else{
                        $(mention).css('display','none');
                    }
                    core.useTemplateAuto(id, res.list,render)
                })
    },
    personNalDetail:function(Id){
        $(Id).click(function (e) {
            if ($(e.target).hasClass('title')) {
                
                // 没有参数
                if($(e.target).attr('data-detailurl')=="/knowledge.html"||$(e.target).attr('data-detailurl')=="/resourseDetail.html"||$(e.target).attr('data-detailurl')=='/researchArchives.html'){
                   window.open('/resourseDetail.html'+$(e.target).attr('data-ipaddress')) 
                }
                //有参数入口详情页
                if ($(e.target).attr('data-detailurl')=='/magazineDetail.html') {
                   // 插入浏览量 内部
                   window.open('/magazineDetail.html'+$(e.target).attr('data-ipaddress')) 
                }//都不满足
                else{
                    // 外部资源接口 
                    pageData.isOutVisited($(e.target))
                    window.open($(e.target).attr('data-detailUrl'))
                }
            }
        })
    },
    //获取json配置中isopen数据
    getIsOpen:function(data){
        var list=[];
        for (var d = 0; d <data.length; d++) {
            if (data[d]['isOpen']) {
               list.push(data[d])
            }
        }
        return list;
    },
     // 深拷贝
    deepclone:function(obj){
        var newDate=Array.isArray(obj)?[]:{};
        if(obj&&typeof obj==='object'){
            for(var k in obj){
                if(obj[k]&&typeof obj[k]==='object'){
                    newDate[k]=deepclone(obj[k]);
                }else{
                    newDate[k]=obj[k];
                }
            }
        }
        return newDate;
       }
    }
    return pageData;
}));
